/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.wuhenzhizao.ohostitlebar.adapter;

import ohos.aafwk.ability.AbilitySlice;
import ohos.agp.components.*;

import org.wuhenzhizao.ohostitlebar.ResourceTable;
import org.wuhenzhizao.ohostitlebar.beans.ListBean;
import org.wuhenzhizao.titlebar.widget.RippleView;

import java.util.List;

/**
 * ListItemProvider
 *
 * @since 2021-06-08
 */
public class ListItemProvider extends BaseItemProvider {
    private List<ListBean> list;
    private AbilitySlice slice;

    /**
     * 构造
     *
     * @param list  数据源
     * @param slice AbilitySlice
     */
    public ListItemProvider(List<ListBean> list, AbilitySlice slice) {
        this.list = list;
        this.slice = slice;
        this.notifyDataChanged();
    }

    @Override
    public int getCount() {
        return list == null ? 0 : list.size();
    }

    @Override
    public Object getItem(int position) {
        if (list != null && position >= 0 && position < list.size()) {
            return list.get(position);
        }
        return null;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public Component getComponent(int position, Component convertComponent, ComponentContainer componentContainer) {
        final Component cpt;
        if (convertComponent == null) {
            cpt = LayoutScatter.getInstance(slice).parse(ResourceTable.Layout_layout_item_sample, null, false);
        } else {
            cpt = convertComponent;
        }
        ListBean mText = list.get(position);
        RippleView text = (RippleView) cpt.findComponentById(ResourceTable.Id_item_text);
        text.setText(mText.getText());

        return cpt;
    }
}